<script lang="ts" setup>
import mcht from '@/api/mcht'
import { useAppStore, useHomeStore } from '@/store'
import { throttle } from '@/utils/shared.ts'
import dayjs from 'dayjs'

const minDate = dayjs().subtract(3, 'month').format('YYYY-MM-DD HH:mm')
const maxDate = dayjs().subtract(1, 'minute').format('YYYY-MM-DD HH:mm')
const {
  windowHeight,
  customBarHeight,
} = storeToRefs(useAppStore())
const { mchtNo, modifyEmployee, bit8, roleFlag } = storeToRefs(useHomeStore())

const form = reactive({
  startDate_line: dayjs().subtract(6, 'day').format('YYYY-MM-DD HH:mm'),
  endDate_line: dayjs().subtract(1, 'minute').format('YYYY-MM-DD HH:mm'),
  mchtNo: '',
  mchtName: '',
  shopId: '',
  shopName: '',
  employeeNo: '',
  sysSeqNum: '',
  transStatus: '',
})

const statusOptions = [
  { value: '01', text: '交易中' },
  { value: '02', text: '成功' },
  { value: '03', text: '失败' },
  { value: '04', text: '超时' },
]

function statusName(status: string) {
  return {
    '01': '交易中',
    '02': '成功',
    '03': '失败',
    '04': '超时',
  }[status]
}

const mchtList = ref([])
const mchtOptions = ref<Option[]>([])
const shopOptions = ref<Option[]>([])
async function getStoreList() {
  const { data } = await mcht.getMchtStoreList()
  if (data.status === 'success') {
    mchtList.value = data?.data.mchtList
    mchtOptions.value = mchtList.value.map((mcht) => {
      return {
        text: mcht.mchtNm,
        value: mcht.mchtNo,
      }
    })
    // 赋值以触发watch
    form.mchtNo = mchtNo.value
  }
}

const employeeList = ref([])
async function getEmpList() {
  const { data } = await mcht.getEmpList({
    mchtNo: form.mchtNo,
    shopId: form.shopId,
  })
  if (data.status === 'success') {
    employeeList.value = data.data.employeeList.map((employee: any) => {
      return Object.assign(employee, {
        text: `${employee.phoneNumber}-${employee.employeeName}`,
        value: employee.employeeNo,
      })
    })
  }
}

// 切换商户
watch(() => form.mchtNo, async () => {
  // 清空
  form.shopId = ''
  form.shopName = ''
  form.employeeNo = ''

  form.mchtName = mchtOptions.value.find(x => x.value === form.mchtNo).text
  shopOptions.value = mchtList.value.find(x => x.mchtNo === form.mchtNo).shops.map((shop) => {
    return {
      text: shop.shopNm,
      value: shop.shopId,
    }
  })
  await getEmpList()
})

// 切换门店
watch(() => form.shopId, async () => {
  form.employeeNo = ''
  form.shopName = shopOptions.value.find(x => x.value === form.shopId).text
  await getEmpList()
})

onMounted(async () => {
  await getStoreList()
})

const ruleForm = ref()
const rules = {
  employeeNo: [
    { required: true, message: '请选择员工/店员' },
  ],
}

const total = ref(0)
const page = ref(1)
const list = ref([])
const pageSize = ref(5)
const loading = ref<boolean>(false)
const end = ref<boolean>(false)

const transAmtSum = ref('')
const transCount = ref('')
const transFeeSum = ref('')

const throttledGetList = throttle(getList, 600)

async function query() {
  list.value = []
  // getList(1)
  throttledGetList(1)
}

async function getList(p: number) {
  ruleForm.value.validate().then(async ({ valid }: { valid: boolean }) => {
    if (valid) {
      const { data } = await mcht.getQrOrders(Object.assign(form, {
        pageNum: p,
        pageSize: pageSize.value,
        startDate: convertDateFormat(form.startDate_line) + '00',
        endDate: convertDateFormat(form.endDate_line) + '00',
      }))
      if (data?.status === 'success') {
        total.value = data.data.total
        page.value = data.data.pageNum

        transAmtSum.value = data.data.transAmtSum
        transCount.value = data.data.transCount
        transFeeSum.value = data.data.transFeeSum

        let lists = data.data.orders
        lists.forEach((e) => {
          e.fristName = e.txnDesc.charAt(0)
        })

        list.value = list.value.concat(lists)

        if (page.value * pageSize.value >= total.value) {
          end.value = true
        }
        else {
          end.value = false
        }
      }
    }
  })
}

function scrolltolower() {
  if (!end.value) {
    getList(page.value + 1)
  }
}

function convertDateFormat(dateString) {
  // 检查输入的格式是否正确
  // const datePattern = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
  // if (!datePattern.test(dateString)) {
  //   throw new Error("输入格式不正确，应为 'YYYY-MM-DD HH:mm:ss'");
  // }
  const datePattern = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/;
  if (!datePattern.test(dateString)) {
    throw new Error("输入格式不正确，应为 'YYYY-MM-DD HH:mm'");
  }

  // 替换，并去除连接符和空格
  return dateString.replace(/[- :]/g, '');
}

const popupMask = ref<boolean>(false)
const popupContainer = ref<boolean>(false)
const searchKey = ref<string>('全部')

function show_popup() {
  popupMask.value = true
  popupContainer.value = true
}

function hide_popup() {
  popupMask.value = false
  popupContainer.value = false
}

function searchList() {
  const info = employeeList.value.find(item => item.employeeNo === form.employeeNo)
  let employee = ''
  if (info){
    employee = info.phoneNumber + '-' + info.employeeName
  }
  
  let result = [form.startDate_line, form.endDate_line, form.mchtName, form.shopName, employee, form.sysSeqNum, statusName(form.transStatus)]
    .filter(item => item)
    .join('/');
  if (!result) {
    result = '全部'
  }
  searchKey.value = result
  resetList()
  query()
  hide_popup()
}
function clearSearchList() {
  resetForm()
  searchKey.value = '全部'
  resetList()
  query()
}

function resetForm() {
  form.startDate_line = dayjs().subtract(6, 'day').format('YYYY-MM-DD HH:mm')
  form.endDate_line = dayjs().format('YYYY-MM-DD HH:mm')
  form.sysSeqNum= ''
  form.transStatus= ''
}

function resetList() {
  list.value = []
  total.value = 0
  page.value = 1
  end.value = false
}
</script>

<template>
  <!-- 弹出框结构 -->
  <div class="li-popup">
    <div class="popup-mask" :class="popupMask ? 'popup-mask-show' : ''" @click="hide_popup">
    </div>
    <div class="popup-container" :class="popupContainer ? 'popup-container-show' : ''">
      <div class="popup-content">
        <div class="popup-body">
          <nut-form ref="ruleForm" :model-value="form" :rules="rules">

            <nut-form-item label="起始日期">
              <time-picker v-model="form.startDate_line" :min="minDate" :max="maxDate" title="交易起始日期" />
            </nut-form-item>
            <nut-form-item label="结束日期">
              <time-picker v-model="form.endDate_line" :min="minDate" :max="maxDate" title="交易结束日期" />
            </nut-form-item>

            <nut-form-item label="商户名" prop="mchtNo" required>
              <option-select v-model="form.mchtNo" title="商户名" :options="mchtOptions" />
            </nut-form-item>
            <nut-form-item label="门店名" prop="shopId" v-if="shopOptions.length !== 0">
              <option-select v-model="form.shopId" title="门店名" :options="shopOptions" />
            </nut-form-item>

            <nut-form-item :label="!form.shopId ? '员工' : '店员'" prop="employeeNo" required>
              <option-select v-model="form.employeeNo" :title="!form.shopId ? '员工' : '店员'" :options="employeeList" />
            </nut-form-item>

            <nut-form-item label="系统流水号">
              <nut-input v-model="form.sysSeqNum" placeholder="请输入流水号" type="text" />
            </nut-form-item>
            <nut-form-item label="交易状态" prop="transStatus">
              <option-select v-model="form.transStatus" title="交易状态" :options="statusOptions" />
            </nut-form-item>
          </nut-form>
          <div class="li-searchBar-btn">
            <div class="li-cz shake_o" @click="resetForm">重置</div>
            <div class="li-ss shake_o" @click="searchList">搜索</div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="staff">
    <div class="query">

      <div class="li-searchBar">
        <div class="li-rantangle">
          <div class="li-btnleft li-butStyle" :class="searchKey !== '全部' ? 'li-lftactive' : ''"
            @click="clearSearchList">
            <div class="li-texts">{{ searchKey }}</div>
          </div>
          <div class="li-btnright li-butStyle" :class="searchKey !== '全部' ? 'li-ritactive' : ''" @click="show_popup">筛选
          </div>
        </div>
      </div>
      <div style="width: 100%;height: 120rpx;"></div>

    </div>
    <div class="list">
      <div class="li-mpdata-info" v-if="transAmtSum !== ''">
        <div class="li-mpdata-info-item">
          <div class="li-mpdata-info-item-num"><nut-price :price="transAmtSum" symbol="¥"
              custom-style="font-size: 36rpx;font-weight: bold;color: #2196F3" />
          </div>
          <div class="li-mpdata-info-item-name">交易总金额</div>
        </div>
        <div class="li-mpdata-info-item li-mpdata-info-nthchild">
          <div class="li-mpdata-info-item-num">{{ transCount }}</div>
          <div class="li-mpdata-info-item-name">总笔数</div>
        </div>
        <div class="li-mpdata-info-item">
          <div class="li-mpdata-info-item-num"><nut-price :price="transFeeSum" symbol="¥"
              custom-style="font-size: 36rpx;font-weight: bold;color: #2196F3" />
          </div>
          <div class="li-mpdata-info-item-name">总手续费</div>
        </div>
      </div>
      <template v-if="list.length > 0">
        <scroll-view scroll-y :style="{ height: `${windowHeight - customBarHeight - 40 - 40}px` }"
          @scrolltolower="scrolltolower">

          <div class="li-card-item shake_o shadow" v-for="(item, index) in list" :key="index">
            <div class="content-box1 b-c1">
              <div class="cb-lft">
                <div class="first">{{ item.fristName }}</div>
                <div class="info">
                  <div class="name">{{ item.txnDesc }}</div>
                  <div class="id">商户号:{{ item.mchtNo }}</div>
                </div>
              </div>
              <div class="cb-rit c1">{{ item.statusDesc }}</div>
            </div>
            <div class="content-box2">
              <div class="item">
                <div class="lable">交易流水号</div>
                <div class="name">{{ item.sysSeqNum }}</div>
              </div>
              <div class="item" v-if="item.shopId">
                <div class="lable">门店号</div>
                <div class="name">{{ item.shopId }}</div>
              </div>
              <div class="item">
                <div class="lable">交易金额</div>
                <div class="name"><nut-price :price="item.transAmt" symbol="¥" custom-style="color: #000" /></div>
              </div>
              <div class="item">
                <div class="lable">结算金额</div>
                <div class="name"><nut-price :price="item.settlementAmount" symbol="¥" custom-style="color: #000" />
                </div>
              </div>
              <div class="item">
                <div class="lable">交易手续费</div>
                <div class="name"><nut-price :price="item.transFee" symbol="¥" custom-style="color: #000" /></div>
              </div>
              <div class="item" v-if="item.activityNo">
                <div class="lable">优惠活动号</div>
                <div class="name">{{ item.activityNo || '无' }}</div>
              </div>
              <div class="item" v-if="item.discountAmount">
                <div class="lable">优惠金额</div>
                <div class="name"><nut-price :price="item.discountAmount" symbol="¥" custom-style="color: #000" /></div>
              </div>
              <div class="item" v-if="item.origSysSeqNum">
                <div class="lable">原交易流水号</div>
                <div class="name">{{ item.origSysSeqNum || '无' }}</div>
              </div>
              <div class="item" v-if="item.qrNo">
                <div class="lable">码牌编号</div>
                <div class="name">{{ item.qrNo }}</div>
              </div>
            </div>
            <div style="padding-bottom: 10rpx;"></div>
          </div>
          <div v-if="end" class="end">没有更多数据了</div>
          <div v-if="loading" class="loading">
            <nut-icon name="loading" />
            数据加载中...
          </div>
        </scroll-view>
      </template>
      <nut-empty v-else description="暂无数据" />
    </div>
  </div>
</template>

<route lang="json">
{
  "layout": "home",
  "style": {
    "navigationBarTitleText": "码牌交易",
    "backgroundColorContent": "#f1f1f1"
  }
}
</route>

<style lang="sass" scoped>
.list
  padding: 20rpx
  .item
    background-color: #fff
    border-radius: 6px
    margin-bottom: 15px
    .top
      display: flex
      justify-content: space-between
      border-bottom: 1px solid #e8e8e8
      padding: 10px 13px
      .title
        color: #8e8e8e
      .right
        color: #2196F3
    .content
      display: flex
      justify-content: space-between
      padding: 12px 18px 0
      .left
        .line
          margin-bottom: 12px
          .key
            display: inline-block
            margin-right: 12px
          .value
            display: inline-block
      .right
        .mod
          margin-bottom: 10px
  .end
    text-align: center
    color: #8e8e8e

/* 筛选按钮相关 end */
:deep(.nut-cell-group__wrap)
  box-shadow: none!important
  margin: 0!important
  padding: 10rpx 0!important

:deep(.nut-cell-group .nut-cell::after)
  border-bottom: none
</style>
